/********************************************************************
 * * 说明：FrmMain.cs
********************************************************************/

using CCWin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using CCWin.SkinControl;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using System.Data.OleDb;
using System.Net.Sockets;
using System.Net;

namespace CTOOLS
{
    public partial class FrmMain : CCSkinMain
    {
    
        System.Timers.Timer pTimer = new System.Timers.Timer(); //声明定时器  //设置定时间隔(毫秒为单位)1秒=1000毫秒
        public static bool BSVTimer = false;//设置定时器状态，true时暂停
        public static int IIsCanConnect = 0;//设置断网时弹出登录框
        public static bool BIsCanConnect = false;//设置断网时弹出登录框
        public static string SessionID = "";//用户登录后的SessionID
        public static string UserID = "";//用户名
        public static string UserPW = "";//用户密码
        public static string UserDQR = "";//用户到期日
        private delegate void LongFCallBack();

        public BackgroundWorker worker;
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        CWordFunc cWordFunc = new CWordFunc();
        WordFileH wordFileH = new WordFileH();
        private string ExePath = "";
        private IniFile iniFile = new IniFile();
        private string Current = "";//当前根目录
        ArrayList wQLRange = new ArrayList();//标点重复 “。。”、“；；”、“，；”、“；，”、“，。”、“。，”、“；。”、“。；”
        ArrayList wSMRange = new ArrayList();
        object oMissing = System.Reflection.Missing.Value;
        /************BackgroundWorker BEGIN*************/
        private Word.Document wDocB = null;
        private string workerType = "";//
        //private string APdfSave = "";
        //private DataTable DTBW = null;
        //private DataRow[] drsA = null;
        //private SkinDataGridView SDGV = null;
        //private string ASJLY = "";
        //private string TMANNNUM = "";
        //private string sErrorB = "";
        //private string fileFullNameB = "";
        //private string spathB = "";
        private bool BFLAGB = false;
        //private int iPB=0, iModelWB=0, iModelHB=0, iXB=0, iYB=0, iWB=0, iHB=0;
        /************BackgroundWorker END*************/
        //创建1个客户端套接字和1个负责监听服务端请求的线程
        SplashScreenManager loading = null;
        //static Thread ThreadSocketClient = null;
        //static Socket SocketClient = null;
        //string sClientIp = "", sClientPort = "", sClientDt="";
        //string sAuthType = "", sKeyPath = "", sServerIp = "", sServerPort = "", sServerUpaddress="";//验证登录
        public FrmMain(string _SessionID, string _UserDQR, string _UserID, string _UserPW)
        {
            SimpleLoading loadingfrm = new SimpleLoading(this);
            //将Loaing窗口，注入到 SplashScreenManager 来管理
            loading = new SplashScreenManager(loadingfrm);
            loading.ShowLoading();
            //try catch 包起来，防止出错
            if (cWordFunc.checkOffice() == 0)
            {
                if (loading.IsNull() == false) loading.CloseWaitForm();
                MessageBox.Show("未检测到合适版本的Office软件!");
                System.Environment.Exit(0);

            }
            if (DsoframerRegister.RegisteDsoframer()==false)
            {
               if(loading.IsNull()==false) loading.CloseWaitForm();
                MessageBox.Show("注册WORD控件失败!");
                System.Environment.Exit(0);
            }
            Current = Directory.GetCurrentDirectory();//获取当前根目录
            InitializeComponent();

            SessionID = _SessionID;
            UserDQR = _UserDQR;
            UserID = _UserID;
            UserPW = _UserPW;

            ExePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            iniFile.path = ExePath + "system.ini";
            skinLSave.Text= iniFile.IniReadValue("SavePath", "FSPath");
            skinLabelUPV.Text = iniFile.IniReadValue("UPDATEV", "VNUM");
          


            //设置自动换行
            this.dataGridViewMsg.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            //设置自动调整高度
            this.dataGridViewMsg.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            worker = new BackgroundWorker();
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.WorkerReportsProgress = true;
            loading.CloseWaitForm();
        }

        
        /// <summary>
        /// 异步 开始事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //需要执行的代码
            //Thread.Sleep(1000);  //让进程上卡半秒钟
            if (workerType == "Check_Word_Range")
            {
                BFLAGB = cWordFunc.Check_Word_Range(worker,ref wDocB, ref wQLRange, ref wSMRange);
            }
            
        }

        /// <summary>
        /// 事件: 异步执行完成后 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            worker.DoWork -= worker_DoWork;
        }


        //选项卡选中时触发
        private void tabShow_SelectedIndexChanged(object sender, EventArgs e) {
            if(tabShow.SelectedIndex == 0 )
            {
                skinLabelROWCOUNT.Text = dataGridViewMsg.RowCount.ToString();
                skinLabelROWCOUNT.Visible = true;
                skinLabel10.Visible = true;
                //将焦点给web浏览器控件
                //webNew.Focus();
            }
            else
            {
                skinLabelROWCOUNT.Visible = false;
                skinLabel10.Visible = false;
            }
        }

  
        private void tabPageEx5_Resize(object sender, EventArgs e)
        {
            skinGroupBoxW.Width = tabPageEx5.Width + 1;
            skinGroupBoxW.Height = tabPageEx5.Height - 18;
            skinButtonOpenQLYQ.Location = new Point(0, 3);
            skinButtonCheck.Location = new Point(65, 3);
            skinButtonPDF.Location = new Point(134, 3);
            skinButtonSave.Location = new Point(221, 3);
            skinButtonPath.Location = new Point(281, 3);
            skinLSave.Location = new Point(374, 10);
            skinGroupBoxA.Height = tabPageEx5.Height - skinPanel2.Height - 10 - 19;
            axFramerControlA.Height = skinGroupBoxA.Height - 25;
        }


        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <returns></returns>
        public string getFolderBrowserDialog()
        {
            string rPath = "";
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.ShowNewFolderButton = false;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                rPath = folderBrowserDialog.SelectedPath;
            }
            return rPath.Trim();
        }


        private void FrmMain_Shown(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Maximized;
            //this.Visible = true;
        }

        private void FrmMain_Resize(object sender, EventArgs e)
        {
            string sValue = skinLabelDBYC.Text;

            skinPanelVX2.Location = new Point(this.Width - skinPanelVX2.Width - 10 , 27);
            skinLabelFWDQSJ.Location = new Point(373, skinPanelVX2.Location.Y + skinPanelVX2.Height - 20);
            tabPageEx5.Width = this.Width;
            //
            skinGroupBoxA.Width = tabPageEx5.Width - dataGridViewMsg.Width  - 1;
            axFramerControlA.Width = skinGroupBoxA.Width - 8;

            dataGridViewMsg.Location = new Point(tabPageEx5.Width - dataGridViewMsg.Width, 25);
            dataGridViewMsg.Height= tabPageEx5.Height - skinPanel2.Height - 17;
            skinLabelDBYC.Location = new Point(tabPageEx5.Width - dataGridViewMsg.Width , 8);

            skinGroupBoxA.Height = tabPageEx5.Height - skinPanel2.Height - 7;
            axFramerControlA.Height = skinGroupBoxA.Height - 25;

         
            skinPanelhelp.Location = new Point(this.Width - 110 + 4, 3);
            skinLabelROWCOUNT.Location = new Point(this.Width - dataGridViewMsg.Width + skinLabel10.Width - 10, skinLabel8.Location.Y);
            skinLabel10.Location = new Point(this.Width - dataGridViewMsg.Width, skinLabel8.Location.Y);

        }

        private void skinLabelDBYC_Click(object sender, EventArgs e)
        {
            string sValue=skinLabelDBYC.Text;
            if (sValue.Equals("隐藏对比结果"))
            {
                skinLabelDBYC.Text = "显示对比结果";
                dataGridViewMsg.Visible = false;
                skinLabelDBYC.Location = new Point(tabPageEx5.Width - skinLabelDBYC.Width, 8);
                skinGroupBoxA.Width= tabPageEx5.Width - 1;
                axFramerControlA.Width = skinGroupBoxA.Width - 8;
            }
            else
            {
                skinLabelDBYC.Text = "隐藏对比结果";
                dataGridViewMsg.Visible = true;
                skinLabelDBYC.Location = new Point(tabPageEx5.Width - dataGridViewMsg.Width, 8);
                skinGroupBoxA.Width = tabPageEx5.Width - dataGridViewMsg.Width - 1;
                axFramerControlA.Width = skinGroupBoxA.Width - 8;
            }
           
        }
        /// <summary>
        /// 打开权利要求书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButtonOpenQLYQ_Click(object sender, EventArgs e)
        {
            openFileQLYQandSMS("QLYQ");
        }
       
        private void skinButtonPDF_Click(object sender, EventArgs e)
        {
            if (checkDsoframer() == false) return;
            string savePath = skinLSave.Text;
            if (checkFilePath(savePath) == false) return;
            Word.Document wDoc = null;
            try
            {
                wDoc = axFramerControlA.ActiveDocument as Word.Document;
                if (wDoc.Saved==false)
                {
                    wDoc.Save();
                }
                int officev = cWordFunc.checkOffice();
                setWordRBC(wDoc, Word.WdColorIndex.wdAuto);//去掉黄色选择颜色
                if (wordFileH.WordSplitPdf(ref wDoc, axFramerControlA.DocumentName, savePath, officev))
                {
                    MessageBox.Show("文件拆分成功!");
                }
                else
                {
                    MessageBox.Show("文件拆分失败!");
                }
            }
            catch (Exception em)
            {
                log.Error("按分节符拆分转换PDF出错", em);
            }
           
        }
        private void skinButtonPath_Click(object sender, EventArgs e)
        {
            string ls_path = PubFunClass.GetSelectPath();
            if (string.IsNullOrEmpty(ls_path) == false)
            {
                skinLSave.Text = ls_path;
                iniFile.IniWriteValue("SavePath", "FSPath", ls_path);
            }
        }


        private void skinLSave_DoubleClick(object sender, EventArgs e)
        {
            string spath = "";
            spath = skinLSave.Text.Trim();
            if (string.IsNullOrEmpty(spath) == false)
            {
                System.Diagnostics.Process.Start("explorer.exe", spath);// "/select,\"C:\\a.txt\"");
            }
        }

        /// <summary>
        /// 打开权利要求或说明书
        /// </summary>
        /// <param name="sfileType"></param>
        private void openFileQLYQandSMS(string sfileType)
        {
            string fileName = "";
            string fileFullName = "";
            PubFunClass.getFileDialog(Current, "word files (*.doc,*.docx)|*.doc;*.docx", ref fileName, ref fileFullName);
            if (fileName.IsNullOrEmpty() == false)
            {
                if (PubFunClass.isFileLocked(fileFullName))
                {
                    MessageBox.Show("文件["+ fileName + "]已被其它程序打开!");
                }
                else
                {
                    skinGroupBoxA.Text = fileName;
                    axFramerControlA.Open(fileFullName);
                }
            }
        }

        private void dataGridViewMsg_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex>=0 || e.RowIndex >= 0)
            {
                string rId = dataGridViewMsg.Rows[e.RowIndex].Cells[0].Value.ToString();
                string rType = dataGridViewMsg.Rows[e.RowIndex].Cells[2].Value.ToString();
                Word.Document wDoc = axFramerControlA.ActiveDocument as Word.Document;
                int iRId=int.Parse(rId);
                JYResult iJYResult = new JYResult();
                setWordRBC(wDoc, Word.WdColorIndex.wdAuto);
                if (rType.Equals("QL"))
                {
                    iJYResult = (JYResult)wQLRange[iRId];
                    if (iJYResult == null) return;
                    if (iJYResult.sQStr != null && iJYResult.sQStr.Length > 0)
                    {
                        //Word.Range iJYResult.pRange;

                        //setWordRBC(wDoc, Word.WdColorIndex.wdAuto);
                        cWordFunc.getFindDOCM(ref wDoc,  iJYResult.pRange, iJYResult.sQStr,"");
                    }
                    else
                    {
                       // setWordRBC(wDoc, Word.WdColorIndex.wdAuto);
                        iJYResult.pRange.Select();
                    }

                }
                else if (rType.Equals("SM"))
                {
                    iJYResult = (JYResult)wSMRange[iRId];
                    if (iJYResult == null) return;
                    if (iJYResult.sQStr!=null && iJYResult.sQStr.Length > 0)
                    {
                        //setWordRBC(wDoc, Word.WdColorIndex.wdAuto);
                        cWordFunc.getFindDOCM(ref wDoc, iJYResult.pRange, iJYResult.sQStr, "");

                    }
                    else
                    {
                        //setWordRBC(wDoc, Word.WdColorIndex.wdAuto);
                        iJYResult.pRange.Select();
                    }
                }
                else
                {
                    
                    return;
                }
               
            }
        }
        /// <summary>
        /// 设置word文字背景色
        /// </summary>
        /// <param name="wDoc"></param>
        private void setWordRBC(Word.Document wDoc,Word.WdColorIndex wdC)
        {
            wDoc = axFramerControlA.ActiveDocument as Word.Document;
            for (int j = 1; j <= wDoc.Sections.Count; j++)
            {
                wDoc.Sections[j].Range.HighlightColorIndex = wdC;
            }
        }
        private void dataGridViewMsg_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            string title = (e.RowIndex + 1).ToString();
            Brush bru = Brushes.Black;
            e.Graphics.DrawString(title, dataGridViewMsg.DefaultCellStyle.Font,
                bru, e.RowBounds.Location.X + dataGridViewMsg.RowHeadersWidth / 2 - 4, e.RowBounds.Location.Y + 4);
            //Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dataGridViewMsg.RowHeadersWidth - 4, e.RowBounds.Height);
            //TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dataGridViewMsg.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewMsg.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void skinButtonCheck_Click(object sender, EventArgs e)
        {
            if (checkDsoframer() == false) return;
            
            //=====================================
            this.dataGridViewMsg.Rows.Clear();
            Word.Document wDoc = axFramerControlA.ActiveDocument as Word.Document;

            wDocB = wDoc;
            workerType = "Check_Word_Range";
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();
            worker.ReportProgress(0, "正在读取数据......");
            //显示进度窗体
            LoadForm frm = new LoadForm(ref worker, 6);
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog(this);

            //cWordFunc.Check_Word_Range(ref wDoc, ref wQLRange, ref wSMRange, this);
            int index = 0;
            foreach (JYResult iJYResult in wQLRange)
            {
                index = this.dataGridViewMsg.Rows.Add();
                this.dataGridViewMsg.Rows[index].Cells[0].Value = iJYResult.rNum;
                this.dataGridViewMsg.Rows[index].Cells[1].Value = iJYResult.sText;
                this.dataGridViewMsg.Rows[index].Cells[2].Value = iJYResult.sType;
            }
            foreach (JYResult iJYResult in wSMRange)
            {
                index = this.dataGridViewMsg.Rows.Add();
                this.dataGridViewMsg.Rows[index].Cells[0].Value = iJYResult.rNum;
                this.dataGridViewMsg.Rows[index].Cells[1].Value = iJYResult.sText;
                this.dataGridViewMsg.Rows[index].Cells[2].Value = iJYResult.sType;
            }
        }
        //得到文件夹下文件目录
        //string[] dataFiles = Directory.GetFiles(path);
        private bool checkDsoframer()
        {
            if (axFramerControlA == null)
            {
                MessageBox.Show("请先初始化office控件对象！");
                return false;
            }
            else
            {
                if (string.IsNullOrEmpty(axFramerControlA.DocumentFullName) || axFramerControlA.ActiveDocument.IsNull())
                {
                    MessageBox.Show("请先打开Word文档!");
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        private bool checkFilePath(string fPath)
        {
            if (string.IsNullOrEmpty(fPath) || System.IO.Directory.Exists(fPath)==false)
            {
                MessageBox.Show("请选择有效的拆分文件保存路径!");
                return false;
            }
            else
            {
                return true;
            }
        }

        private void skinButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                Word.Document wDoc = axFramerControlA.ActiveDocument as Word.Document;
                if (wDoc.Saved == false)
                {
                    wDoc.Save();
                }
            }
            catch (Exception em)
            {
                log.Error("保存word失败", em);
                MessageBox.Show("保存word失败");
            }
        }

    
   
        private void FrmMain_Load(object sender, EventArgs e)
        {


        }

        private void dataGridViewMsg_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            skinLabelROWCOUNT.Text = dataGridViewMsg.RowCount.ToString();
        }

        private void dataGridViewMsg_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            skinLabelROWCOUNT.Text = dataGridViewMsg.RowCount.ToString();
        }
   
     
        private void skinPanelhelp_Click(object sender, EventArgs e)
        {
            if (!PubFunClass.OpenFile(ExePath + "\\help\\专利文件检查助手使用手册.pdf"))
            {
                MessageBox.Show("打开文件[专利文件检查助手使用手册.pdf]失败!");
            }
        }
    }
}
